#coding=utf-8
import os

import yaml
import time
from source.util.LogUtil import Log,log
from source.util.ConfigUtil import ConfigIni
import random
from source.util.GetCase import case_yaml_file,read_yaml
import source.core.ExecutorService as ExecutorService
from source.util.AdbUtils import ADB
import BaseOperate
from source.util.CaptureCardUtil import CaptureCard
# from TST.CaptureCard import *
import copy
from source.util.DateTimeUtil import *
from source.util.GenerateReports import GenerateReports
from datetime import datetime
from source.util.Performance import make_graph,make_mem_picture
from threading import Thread

from source.util.CommonUtil import getProjectDir
import csv

import sys
reload(sys)
sys.setdefaultencoding('utf8')

class RunApp:

    def __init__(self,device_info,file_list):
        '''
        self.time:存放文件的目录
        :param device:
        '''
        # self.time=time.strftime('%Y-%m-%d_%H_%M_%S',time.localtime(time.time()))
        self.device_info=device_info
        self.device_name=self.device_info['deviceName']
        self.adb=ADB(self.device_name)
        self.driver=BaseOperate.Base(self.adb)
        self.runFlag=True
        self.file_list=file_list
        self.ini = ConfigIni()


    @log()
    def mkdir_file(self,parent_dir):
        '''
        :return: 返回文件列表
        '''
        result_file=str(self.ini.get_ini('test_case','log_file'))+'/'+self.device_name.replace('.', '-').replace(':', "-")+'/'+parent_dir
        # print('self.device===',str(self.device_info))
        if not os.path.exists(result_file):
            os.makedirs(result_file)
        result_file_every=result_file+'/'+time.strftime("%Y-%m-%d_%H_%M_%S{}".format(random.randint(10, 99)),
                                          time.localtime(time.time()))
        if not os.path.exists(result_file):
            os.mkdir(result_file)
        if not os.path.exists(result_file_every):
            os.mkdir(result_file_every)

        file_list=[
            result_file_every+'/log',
            result_file_every + '/per',
            result_file_every + '/img',
            result_file_every + '/status',
            result_file_every + '/match_pics',
        ]

        for file_path in file_list:
            if not os.path.exists(file_path):
                os.mkdir(file_path)
        return file_list

    # def collectCpuAndMem(self,package_name):
    #     while self.runFlag:
    #         cpu =  self.adb.get_cpu(package_name)
    #         mem =  self.adb.get_mem(package_name)
    #         collect_time=datetime.now().strftime('%H:%M:%S.%f')
    #         cpu_list.append({'time':collect_time,"cpu_value":cpu})
    #         mem_list.append({'time':collect_time,"mem_value":mem})
    #         time.sleep(0.2)

    @log()
    def parseYaml(self, yaml_name, yaml_path,capture_card):
        '''
        已经启动
        :param yaml_name:yaml文件名
        :param yaml_path:yaml文件路径
        :return:
        '''
        exService= ExecutorService.Executor(
            self.driver,
            yaml_name,
            yaml_path,
            self.all_result_path,
            self.device_name,
            self.device_info,
            self.logger,
            capture_card
        )
        self.case_cpu_list=[]
        self.case_mem_list=[]
        exService.execute(self.case_cpu_list,self.case_mem_list)
        pass

    @log()
    def case_start(self):
        '''
        生成一个日志记录器

        控制driver开启和关闭，
        1.开启driver，并且执行测试
        2.关闭driver
        3.清理logcat appium进程
        :return:
        '''
        case_parent_dir=get_time("%Y%m%d%H%M%S")
        if self.file_list:
            # 如果有传入文件，则运行指定文件
            if os.path.isfile(self.file_list[0][1]):
                test_case_yaml = self.file_list
                pass
            else:
                test_case_yaml=case_yaml_file(self.file_list[0]).items()
            pass
        else:
            # 如果没有传入文件，则运行所有
            test_case_yaml=case_yaml_file().items()

        if test_case_yaml:
            thread_start=False
            capture_card=None
            try:
                capture_card = self.initCaptureCard()
                if not capture_card:
                    return
                for yaml_name,yaml_path in test_case_yaml:
                    try:

                        filename = yaml_name.rsplit('.', 1)[0]
                        print "being exec script="+filename
                        if filename.endswith('base'):
                            continue
                        self.all_result_path = self.mkdir_file(case_parent_dir)
                        self.logger = Log(self.all_result_path[0])
                        self.logger.info('yaml path:{}'.format(yaml_path))
                        self.ini.set_ini("test","index",0)   #初始化截图索引点
                        if not thread_start:
                            self.test_apk_package_name=read_yaml(yaml_path)["settings"]["package_name"]
                            t = Thread(target=self.collectCpuAndMem, )
                            t.setDaemon(True)
                            t.start()
                            thread_start = True
                        print "proceeding ........"
                        #TODO 解析yaml文件，执行脚本
                        self.parseYaml(yaml_name, yaml_path,capture_card)
                        #单脚本多任务结束后清空缓存，回到home
                        # os.system('adb -s {} shell pm clear {}'.format(self.device,self.device_info['appPackage']))
                        # time.sleep(2)
                    except Exception as e:
                        self.logger.error('driver quit error=' +str(e))
                    finally:
                        # if capture_card:
                        #     capture_card.close()
                        print "end exec script"
                        os.chdir(getProjectDir())
                        if self.driver.current_package()!= self.device_info['appPackage']:
                            self.driver.send_key_event(3)
                            # os.system('adb -s {} shell input keyevent 3'.format(self.device_name))
                        time.sleep(3)
                        self.logger.info('当前任务执行结束')
                        try:
                            for handler in self.logger.handlers:
                                handler.close()
                        except Exception as e:
                            print str(e)
                self.runFlag = False
                self.save_cpu_mem(cpu_list,mem_list,self.logger)
                self.generate_unify_test_report()
                # 运行结束后，需要关闭cmd,node等进程
            except Exception as e:
                if self.logger:
                    self.logger.error('driver quit error %s' % e)
                else:
                    Log().info('logger 对象没有初始化.......')
            finally:
                if capture_card:
                    capture_card.close()
                time.sleep(5)
                print "Test Finished."
        else:
            print("not yaml found")
    pass

    def initCaptureCard(self,retry_times=3):
        if retry_times<0:
            return None
        capture_card = CaptureCard()
        if not capture_card:
            print "please check capture card status..."
            print "retry..."
            sleep(15)
            self.initCaptureCard(retry_times=retry_times-1)
        else:
            return capture_card

    @log()
    def collectCpuAndMem(self):
        global cpu_list, mem_list,used_mem,ava_mem
        cpu_list=[]
        mem_list=[] #记录内存百分比
        used_mem=[] #记录实时内存使用情况
        ava_mem = []  #系统可用内存实时情况
        self.case_cpu_list=[]
        self.case_mem_list=[]
        while self.runFlag:
            cpu_info =  self.adb.get_cpu(self.test_apk_package_name)
            cur_mem_info,mem_percent =  self.adb.get_mem(self.test_apk_package_name)
            collect_time=datetime.now().strftime('%H:%M:%S')
            cpu_list.append({'time':collect_time,"cpu_value":cpu_info})
            self.case_cpu_list.append({'time':collect_time,"cpu_value":cpu_info})
            mem_list.append({'time':collect_time,"mem_value":mem_percent})
            self.case_mem_list.append({'time':collect_time,"mem_value":mem_percent})
            used_mem.append({'time': collect_time, "mem_value": cur_mem_info})
            #记录当前系统剩余内存
            ava_mem.append({'time': collect_time, "ava_mem_value": self.adb.get_mem_avaliable()})

    @log()
    def save_cpu_mem(self, cpu_list, mem_list,logger):
        pic_file_path = os.path.dirname(os.path.dirname(self.all_result_path[0])) + '/{}.png'
        #make_graph(cpu_list, mem_list,pic_file_path.format("statistic"),logger)
        #make_mem_picture(used_mem,ava_mem,pic_file_path.format("mem"))

        header=["time","cpu_value"]
        cpu_csv = os.path.dirname(os.path.dirname(self.all_result_path[0])) + '/cpu_stat.csv'
        with open(cpu_csv, 'w') as f:
            f_csv = csv.DictWriter(f, header)
            f_csv.writeheader()
            f_csv.writerows(cpu_list)
            pass
        header = ["time", "mem_value"]
        mem_csv = os.path.dirname(os.path.dirname(self.all_result_path[0])) + '/mem_stat.csv'
        with open(mem_csv, 'w') as f:
            f_csv = csv.DictWriter(f, header)
            f_csv.writeheader()
            f_csv.writerows(used_mem)
            pass

        return pic_file_path

    @log()
    def generate_unify_test_report(self):
        '''
        整合成一份测试报告
        '''
        result = GenerateReports(os.path.dirname(os.path.dirname(self.all_result_path[0])), self.device_name)
        #result.make(show_statistic_image=True)
        result.make()
@log()
def get_device_info():
    '''
    获取当前电脑连接的设备
    :return: 设备列表
    '''
    device_list=[]
    ini=ConfigIni()
    test_device=ini.get_ini('test_device','device')

    launcher_package_name=ini.get_ini('test_device','launcher_package_name')

    with open(test_device) as f:
        for device in yaml.load(f):
            device['appPackage']=launcher_package_name
            device_list.append(device)
    return device_list

def update_device_info(device_info):
    ini = ConfigIni()
    test_info = ini.get_ini('test_info', 'info')
    with open(test_info) as f:
        test_dict = yaml.load(f)[0]
    tmp_dict = copy.deepcopy(test_dict)
    tmp_dict.update(device_info)
    return tmp_dict


if __name__ == '__main__':
    # try:
    #     remote = "http://127.0.0.1:" + str(4723) + "/wd/hub"
    #     device_info="{'appPackage': 'com.tcl.cyberui', 'appActivity': '.MainActivity'," \
    #                 "'appWaitActivity': '.MainActivity', 'unicodeKeyboard': True, 'resetKeyboard': True, " \
    #                 "'noReset': True, 'deviceName': '192.168.1.101:5555', 'platformName': 'Android', 'platformVersion': '6.0'}"
    #     driver = webdriver.Remote(remote, eval(device_info))
    #     print(driver)
    # except Exception as e:
    #     print(e)
    # print(get_device_info())
    # from source.util.CommonUtil import getProjectDir
    # capture=CaptureCard()
    # path=r"E:\python\project\TerminateAutoTest\TestResult\192-168-1-107-5555\2019-03-01_12_32_5693"
    # os.chdir(path)
    # capture.takePicture(r"img\1.jpg")
    # os.chdir(getProjectDir())
    # print(os.getcwd())
    cpu_list=[{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},{"a":1,"b":2},
              {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2}, {"a": 1, "b": 2},
              {"a": 1, "b": 2}, {"a": 1, "b": 2}]
    header=["a", "b"]
    with open("a.csv", 'w') as f:
        f_csv = csv.DictWriter(f,header)
        f_csv.writeheader()
        # f_csv = csv.writer(f)
        # f_csv.writerow(headers)

        f_csv.writerows(cpu_list)
        pass
    pass